package com.haitaoit.chengquan.utils;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 通用工具类
 */
public class Utils {

    /**
     * 得到两个时间差的毫秒数 getTime(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param endDate
     * @param startDate
     * @return long
     * @since 1.0.0
     */
    public static long getPoorTime(String endDate, String startDate) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long diff = 0;
        try {
            Date d1 = df.parse(endDate);
            Date d2 = df.parse(startDate);
            diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别
        } catch (Exception e) {
        }
        return diff;
    }

    /**
     * 时 getShowTime1(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param diff
     * @return String
     * @since 1.0.0
     */
    public static String getHourTime(long diff) {
        String hms = "";
        long hours = diff / (1000 * 60 * 60);
        hms = hours + "";
        return hms;
    }

    /**
     * 分 getMinuteTime(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param diff
     * @return String
     * @since 1.0.0
     */
    public static String getMinuteTime(long diff) {
        String hms = "";
        long hours = diff / (1000 * 60 * 60);
        long minutes = (diff - hours * (1000 * 60 * 60)) / (1000 * 60);
        hms = minutes + "";
        return hms;
    }

    /**
     * 秒 getSecondTime(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param diff
     * @return String
     * @since 1.0.0
     */
    public static String getSecondTime(long diff) {
        String hms = "";
        long hours = diff / (1000 * 60 * 60);
        long minutes = (diff - hours * (1000 * 60 * 60)) / (1000 * 60);
        long seconds = (diff - hours * (1000 * 60 * 60) - minutes * (1000 * 60)) / (1000);
        hms = seconds + "";
        return hms;
    }

    /**
     * @param value
     * @return
     * @tab 保留两位小数
     */
    public static String getRoundValue(double value) {
        // DecimalFormat df = new DecimalFormat("0.00");
        String st = String.format("%.2f", value);
        return st;
    }

    /**
     * @param i
     * @return
     * @tab 保留一位小数
     */
    public static String meg(double i) {
        DecimalFormat df = new DecimalFormat("0.0");
        String result = df.format(i);
        return result;
    }

    // public static DisplayImageOptions getDefaultImageOptions(Integer...
    // resId) {
    // return new DisplayImageOptions.Builder()
    // .showImageForEmptyUri(
    // (resId != null && resId.length > 0) ? resId[0]
    // : R.drawable.no_img).cacheInMemory(true)
    // .cacheOnDisk(true).imageScaleType(ImageScaleType.NONE)
    // .considerExifParams(true).build();
    // }
    //
    // public static DisplayImageOptions getDefaultImageOptions1(Integer...
    // resId) {
    // return new DisplayImageOptions.Builder()
    // .showImageForEmptyUri(
    // (resId != null && resId.length > 0) ? resId[0]
    // : R.drawable.personage_picture_1).cacheInMemory(true)
    // .cacheOnDisk(true).imageScaleType(ImageScaleType.NONE)
    // .considerExifParams(true).build();
    // }

    // public static SimpleImageLoadingListener getDefaultAnimateListener() {
    // return new SimpleImageLoadingListener() {
    // final List<String> displayedImages = Collections
    // .synchronizedList(new LinkedList<String>());
    //
    // @Override
    // public void onLoadingComplete(String imageUri, View view,
    // Bitmap loadedImage) {
    // if (loadedImage != null) {
    // ImageView imageView = (ImageView) view;
    // boolean firstDisplay = !displayedImages.contains(imageUri);
    // if (firstDisplay) {
    // FadeInBitmapDisplayer.animate(imageView, 500);
    // displayedImages.add(imageUri);
    // }
    // }
    // }
    // };
    // }

    public static long getCurrentTime() {
        return System.currentTimeMillis();
    }

    /**
     * 去掉￥ getRmb(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param string
     * @return Double
     * @since 1.0.0
     */
    public static Double getRmb(String string) {
        double e = 0.0;
        if (!TextUtils.isEmpty(string)) {
            string = string.replaceAll("￥", "");
            e = Double.valueOf(string);
        }
        return e;
    }

    /**
     * @return CharSequence
     * @Title: getCurrentTime
     * @user: ryan.wang
     */
    public static String getCurrentTime(long time, String format) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
        String currentTime = sdf.format(date);
        return currentTime;
    }

    /**
     * @param maxtime
     * @param mintime
     * @return 两个时间的小时差
     * @Title: compareTime
     * @user: ryan.wang
     */
    public static String compareTime(long maxtime, long mintime) {
        long a = (maxtime - mintime);
        // 秒
        int s = (int) (a / 1000);
        // 分
        int min = s / 60;
        // 时
        int h = min / 60;
        if (min < 1 && min > 0) {
            return String.valueOf("刚刚");
        } else if (h < 1 && h > 0) {
            return String.valueOf(min + "分钟前");
        } else if (1 <= h && h < 24) {
            return String.valueOf(h + "小时前");
        } else if (h >= 24) {
            Date date = new Date(mintime);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd  HH:mm", Locale.getDefault());
            String currentTime = sdf.format(date);
            return currentTime;
        }
        return String.valueOf("刚刚");
    }

    /**
     * 获取系统当前时间 "yyyy年MM月dd日   HH:mm:ss"
     *
     * @return
     */
    public static String getCurrentTimes(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    /**
     * @param unicodeStr 如 \u62c9
     * @return String
     * @Title: readUnicode1
     * @user: ryan.wang
     */
    public static String readUnicode(String unicodeStr) {
        StringBuilder buf = new StringBuilder();
        // 因为java转义和正则转义，所以u要这么写
        String[] cc = unicodeStr.split("\\\\u");
        for (String c : cc) {
            if (c.equals(""))
                continue;
            int cInt = Integer.parseInt(c, 16);
            char cChar = (char) cInt;
            buf.append(cChar);
        }
        return buf.toString();
    }

    /**
     * @return double 保留两位小数
     * @Title:
     * @user: zouxianbin
     */
    public static String format(double amount) {
        BigDecimal money = new BigDecimal(amount);
        return money.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + "";
    }

    /**
     * @return double 保留1位小数
     * @Title:
     * @user: zouxianbin
     */
    public static String formats(double amount) {
        BigDecimal money = new BigDecimal(amount);
        return money.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue() + "";
    }

    /**
     * 3位数字格式的编号 form000(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param position
     * @return String
     * @since 1.0.0
     */
    public static String form000(int position) {
        String str = "";
        if (position >= 0 && position < 10) {
            str = "00" + String.valueOf(position);
        } else if (position >= 10 && position < 100) {
            str = "0" + String.valueOf(position);
        } else if (position >= 100 && position < 1000) {
            str = String.valueOf(position);
        }
        return str;
    }

    /**
     * @param context 传入Activity
     * @return int
     * @Title: getScreenWidth
     * @user: ryan.wang
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        return mDisplayMetrics.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        return mDisplayMetrics.heightPixels;
    }

    /**
     * @param dipValue
     * @return int
     * @Title: dip2px
     * @user: ryan.wang
     * @Description: 密度转分辨率
     */
    public static int dip2px(Activity context, float dipValue) {
        DisplayMetrics mDisplayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
        return (int) (dipValue * mDisplayMetrics.scaledDensity);
    }

    /**
     * @param context void
     * @Title: hideInputMethod
     * @user: ryan.wang
     * @Description: 隐藏输入法
     */
    public static void hideInputMethod(Activity context) {
        try {
            // 隐藏输入法
            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
        }
    }

    public static void closeBoard(Context mcontext) {
        InputMethodManager imm = (InputMethodManager) mcontext
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        // imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
        if (imm.isActive()) // 一直是true
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    public static void hideSystemKeyBoard(Context mcontext, View v) {
        InputMethodManager imm = (InputMethodManager) (mcontext)
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    /**
     * @param json
     * @return boolean
     * @Title: isJsonObject
     * @user: ryan.wang
     * @Description: 是否是jsonobject
     */
    public static boolean isJsonObject(String json) {
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(json);
        } catch (JSONException e) {
        }
        return jsonObject == null ? false : true;
    }

    /**
     * 判别手机是否为正确手机号码； 号码段分配如下：
     * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
     * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
     */
    public static boolean isMobileNum(String mobiles) {
        if (mobiles.length()!=11){
            ToastUtils.showToast("您输入的电话号码位数不正确");
            return false;
        }
        Pattern p = Pattern.compile("^0{0,1}(13[0-9]|15[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 大陆手机号格式
     *
     * @param mobiles
     * @return
     * @tab 判断电话号码
     */
    public static boolean isMobileNum1(String mobiles) {
        Pattern p = Pattern.compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 台湾手机号格式 isTaiwanMobile(这里用一句话描述这个方法的作用) (这里描述这个方法适用条件 – 可选)
     *
     * @param mobiles
     * @return boolean
     * @since 1.0.0
     */
    public static boolean isTaiwanMobile(String mobiles) {
        Pattern p = Pattern.compile("^0\\d{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public static boolean isStature(String stature) {
        Pattern p = Pattern.compile("([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*)");
        Matcher m = p.matcher(stature);
        return m.matches();
    }

    /**
     * @param zipString
     * @return
     * @tab 判断邮编是否正确
     */
    public static boolean isZipNO(String zipString) {
        // String str = "^[a-zA-Z0-9 ]{3,12}$";
        String str = "^[1-9]\\d{5}$";
        return Pattern.compile(str).matcher(zipString).matches();
    }

    /**
     * @param email
     * @return
     * @tab 判断邮箱的正则表达式
     */
    public static boolean isEmail(String email) {
        String str = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
        // String str
        // ="^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * @param password
     * @return
     * @tab 判断密码输入是否正确、密码只能为纯数字和英文结合
     */
    public static boolean isPassword(String password) {
//        String str = "(\\d)([a-zA-Z]).{6,16}";
        String str = "^[0-9a-zA-Z]{6,12}$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(password);
        return m.matches();
    }

    public final static String NEWS_STYLE = "<style type=\"text/css\">"
            + "@font-face{ "
            + "font-family:huawenxinwei;"
            + "font-weight:normal;"
            + "font-style:normal;"
            + "src:url('file:///android_asset/huawenxinwei.TTF') format('truetype');"
            + "}"
            + "body{font-size:20px;line-height:25px;word-wrap:break-word;font-family:huawenxinwei;background-color:white;color:#0}"
            + "p{text-indent:2em}"
            + "img{max-width:310px} "
            + "p img{display:block;margin:0 auto}"
            + "a{text-decoration:none;color:#3E62A6}"
            + "h1{padding-top:1em;text-align:center;font-family:default;font-size:23px;line-height:30px}"
            + "</style>";

    /*
     * MD5加密
     */
    private String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (Exception e) {
            e.printStackTrace();
        }

        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            else
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
        }
        return md5StrBuff.substring(8, 24).toString().toUpperCase();
    }

    /**
     * 半角转换为全角
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * 单位转换
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
